package reservationManagement;

import java.util.List;
import exceptions.*;
import loansManagement.Loan;
import jpaUtils.JPAUtil;
import javax.persistence.EntityManager;

import booksManagement.Book;

public class ReservationDAO
{

	public boolean isEmpty(){
		EntityManager entityManager=JPAUtil.getEntityManager();
		if (entityManager.createNamedQuery("findAllReservations").getResultList().isEmpty())
			return true;
		else
			return false;	
	}


		/**
		 */
		public List<Reservation> getContent(){
			EntityManager entityManager=JPAUtil.getEntityManager();
			return ((List<Reservation>)entityManager.createNamedQuery("findAllReservations").getResultList());
		}






		public boolean add(Reservation reservation){
				EntityManager entityManager=JPAUtil.getEntityManager();
		try{
					entityManager.persist(reservation);
				} catch (Exception e) {
					System.err.println("Problem when saving");
					e.printStackTrace();
					return false;
				}
				return true;
			}








			public String toString(){
				EntityManager entityManager=JPAUtil.getEntityManager();
				String result="";
				List<Reservation> theReservations = (List<Reservation>) entityManager.createNamedQuery("findAllReservations").getResultList();
				for (Reservation r : theReservations)
					result += r.toString()+ "\n";
						return result;
			}







			/**
			 */
			public Reservation get(long reservationId) throws LoanExistsException {
				EntityManager entityManager=JPAUtil.getEntityManager();
				Reservation r = (Reservation) entityManager.find(Reservation.class, reservationId);
				if (r ==null) throw new LoanExistsException();
				else return r;
			}
			





			/**
			 */
			public long size(){
				EntityManager entityManager=JPAUtil.getEntityManager();
				return (entityManager.createNamedQuery("findAllReservations").getResultList().size());
			}






			/**
			 */
			public boolean remove(Reservation reservation) throws LoanExistsException {
				EntityManager entityManager=JPAUtil.getEntityManager();
				if (reservation== null) 
					throw new LoanExistsException(); 
				else 
					try{
						entityManager.remove(reservation);
					} catch (Exception pe) {
						System.err.println("problem when deleting an entity ");
						pe.printStackTrace();
						return false;
					}
				return true;	
			}


}
